package org.rainwalk.library.controller;

import cn.hutool.jwt.JWT;
import lombok.RequiredArgsConstructor;
import org.rainwalk.library.api.auth.AuthProperties;
import org.rainwalk.library.api.log.ApiLog;
import org.rainwalk.library.api.model.Response;
import org.rainwalk.library.api.model.ResponseCode;
import org.rainwalk.library.model.dto.LoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * 登录接口
 *
 * @author 趁雨行 2021-07-22 17:23:41
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor(onConstructor_={@Autowired})
public class LoginController {

    private final AuthProperties authProperties;

    /**
     * 登录
     *
     * @param loginDTO
     * @return
     */
    @ApiLog(value = "登录", logParam = false)
    @PostMapping("/login")
    public Response login(@Validated LoginDTO loginDTO) {
        if (!authProperties.getUsername().equals(loginDTO.getUsername())) {
            return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "账号/密码不正确");
        }
        if (!authProperties.getPassword().equals(loginDTO.getPassword())) {
            return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "账号/密码不正确");
        }
        String token = JWT.create()
                .setKey(authProperties.getKey().getBytes())
                .setExpiresAt(Date.from(LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.ofHours(8))))
                .sign();
        return Response.success("登录成功", token);
    }


}
